<?php
//the page for manage the rule hello world
include("../../header.inc");
require_once("../../DataBase.inc");
require_once("../../applicants/view_script.inc");

//include("status.inc");
include ("status_session.php");

echo "<center><h1>Eligibility Rules</h1></center>";
echo "<br/>";

$high_schools = DataBase::select("high_school", null, null, "high_school_name");
$ngos = DataBase::select("ngo", null, null, "ngo_name");

include("actions.inc");
include("calculation.inc");
include("rules_table.inc");

$program_rules = array();
$rules_subjects = array();

//echo $programs[1]["program_id"];
echo "<br /><b>Enter Eligibility Rules For:</b>
            <select onchange=\"location.href='?program_number='+this.value;\">
                <option value='0' selected='selected'>Pleas program name</option>";
foreach ($programs as $p_num) {

    if (isset($_GET["program_number"]) && $_GET["program_number"] == $p_num["program_id"]) {
        echo "<option value='" . $p_num["program_id"] . "'selected='selected'>" . $p_num["program_name"] . "</option>";
    } else {

        echo "<option value='" . $p_num["program_id"] . "'>" . $p_num["program_name"] . "</option>";
    }
}
echo "</select><br />";

foreach ($programs as $p) {
    if (isset($_GET["program_number"]) && $programs[($_GET["program_number"] - 1)]["program_id"] == $_GET["program_number"]) {// the get value of program number is more that array of program id in DB
        $rules = DataBase::select("exam_eligibility_rule", null, array("selection_campaign_id" => $_SESSION["campaign_id"], "program_id" => $p["program_id"]), "exam_eligibility_rule_id");
        $program_rules[$p["program_id"]] = $rules;
        foreach ($rules as $rule) {
            $rule_id = $rule["exam_eligibility_rule_id"];
            $rule_subjects = DataBase::select("exam_eligibility_rule_subjects", null, array("exam_eligibility_rule_id" => $rule_id));
            $rules_subjects[$rule_id] = $rule_subjects;
        }
    }
}
/*
  //foreach ($programs as $p) {
  //    $rules = DataBase::select("exam_eligibility_rule", null, array("selection_campaign_id" => $_SESSION["campaign_id"], "program_id" => $p["program_id"]), "exam_eligibility_rule_id");
  //    $program_rules[$p["program_id"]] = $rules;
  //    foreach ($rules as $rule) {
  //        $rule_id = $rule["exam_eligibility_rule_id"];
  //        $rule_subjects = DataBase::select("exam_eligibility_rule_subjects", null, array("exam_eligibility_rule_id" => $rule_id));
  //        $rules_subjects[$rule_id] = $rule_subjects;
  //    }
  //} */

echo "According to the rules specified below, here is the status:<ul style='margin:0px'>";
$other_programs_id = array();

foreach ($programs as $p) {
    if (isset($_GET["program_number"]) && $programs[($_GET["program_number"] - 1)]["program_id"] == $_GET["program_number"]) {// the get value of program number is more that array of program id in DB
        echo "<li>";
        echo $p["program_name"];
        echo ": ";
        $rules = $program_rules[$p["program_id"]];
        if ($rules == false || count($rules) == 0) {
            echo "<span style='color:red'>No rule defined yet.</span><br/>";
            break;
        }
        if (count($other_programs_id) > 0) {
            $q = "SELECT SEX,NGO_ID FROM (" . query_eligibles_for_program_and_not_for_others($p["program_id"], $other_programs_id, $program_rules, $rules_subjects) . ") AS toto";
        } else {
            $q = "SELECT SEX,NGO_ID FROM " . query_eligibles_for_program($p["program_id"], $rules, $rules_subjects);
        }
        $res = DataBase::query($q);
        if ($res === false)
            $res = array();
        $nbMales = 0;
        $nbFemales = 0;
        $nbNGO = 0;
        foreach ($res as $r) {
            if ($r["SEX"] == "F")
                $nbFemales++; else
                $nbMales++;
            if ($r["NGO_ID"] <> null)
                $nbNGO++;
        }
        echo count($res) . " eligibles (" . $nbMales . " males, " . $nbFemales . " females, " . $nbNGO . " from NGO)";
        echo "</li>";
        array_push($other_programs_id, $p["program_id"]);
    }
}

echo "</ul>";

echo "<a href='../../stats/eligibility.php'>See rules overview and statistics</a><br/><br/>";

$all_ok = true;
$select_program= false;
$other_programs_id = array();
//Start comment for display the rule

foreach ($programs as $p) {
    if (isset($_GET["program_number"]) && $p["program_id"] == $_GET["program_number"]) {// the get value of program number is more that array of program id in DB
        $select_program= true;
        echo "<button onclick=\"location.href='?'\">Refresh</button>";
        echo "<form name='rules_" . $p["program_id"] . "' onsubmit='return false'>";
        echo "<div style='border: 1px solid black;padding:5px'>";
        echo "<center><h2 style='margin:0px'>" . $p["program_name"] . " Rules</h2></center><br/>";
        $rules = $program_rules[$p["program_id"]];
        if ($rules == false || count($rules) == 0) {
            echo "<span style='color:red'>No rule defined yet.</span><br/>";
            $ok = false;
        } else {
            $ok = build_rules_table($p["program_id"], $rules);
        }
        echo "<a href='?program_number=".$_GET["program_number"]."&create_rule=" . $p['program_id'] . "'>Add a new rule for " . $p["program_name"] . "</a>";
        echo "<br/><br/>";
        if ($ok) {
            $has_threshold = false;

            echo nb_applicants_eligible_for_program($p["program_id"], $rules, $rules_subjects, 0) . " applicant(s) have all the minimum marks<br/>";
            echo nb_applicants_eligible_for_program($p["program_id"], $rules, $rules_subjects, 1) . " applicant(s) have at least 1 threshold<br/>";
            echo "To be eligible, an applicant must have all the minimum marks AND have at least 1 threshold (except if no threshold rule is defined).<br/>";
            if (count($other_programs_id) > 0) {
                echo "Total applicants satisfying " . $p["program_name"] . " eligibility rules:</b> " . nb_applicants_eligible_for_program($p["program_id"], $rules, $rules_subjects) . "<br/>";
                $q = "SELECT COUNT(APPLICANT_ID) FROM (" . query_eligibles_for_program_and_not_for_others($p["program_id"], $other_programs_id, $program_rules, $rules_subjects) . ") AS toto";
                $res = DataBase::query($q);
                $nb = $res[0][0];
                echo "<b>Finally</b>, excluding applicants eligible for previous programs, " . $nb . " are eligible for " . $p["program_name"];
            } else {
                echo "<b>Total eligible applicants for " . $p["program_name"] . " program:</b> " . nb_applicants_eligible_for_program($p["program_id"], $rules, $rules_subjects) . "<br/>";
            }
        } else
            $all_ok = false;
        echo "</div><br/>";
        echo "</form>";
        array_push($other_programs_id, $p["program_id"]);
    }else if(!$select_program){
        $all_ok = false;
    }
}
//End comment for display the rule
//
//
//
//foreach ($programs as $p) {
//	echo "<button onclick=\"location.href='?'\">Refresh</button>";
//	echo "<form name='rules_".$p["program_id"]."' onsubmit='return false'>";
//	echo "<div style='border: 1px solid black;padding:5px'>";
//	echo "<center><h2 style='margin:0px'>".$p["program_name"]." Rules</h2></center><br/>";
//	$rules = $program_rules[$p["program_id"]];
//	if ($rules == false || count($rules)==0) {
//		echo "<span style='color:red'>No rule defined yet.</span><br/>";
//		$ok = false;
//	} else {
//		$ok = build_rules_table($p["program_id"],$rules);
//	}
//	echo "<a href='?create_rule=".$p['program_id']."'>Add a new rule for ".$p["program_name"]."</a>";
//	echo "<br/><br/>";
//	if ($ok) {
//		$has_threshold = false;
//
//		echo nb_applicants_eligible_for_program($p["program_id"],$rules, $rules_subjects,0)." applicant(s) have all the minimum marks<br/>";
//		echo nb_applicants_eligible_for_program($p["program_id"],$rules, $rules_subjects,1)." applicant(s) have at least 1 threshold<br/>";
//		echo "To be eligible, an applicant must have all the minimum marks AND have at least 1 threshold (except if no threshold rule is defined).<br/>";
//		if (count($other_programs_id)>0) {
//			echo "Total applicants satisfying ".$p["program_name"]." eligibility rules:</b> ".nb_applicants_eligible_for_program($p["program_id"],$rules, $rules_subjects)."<br/>";
//			$q = "SELECT COUNT(APPLICANT_ID) FROM (".query_eligibles_for_program_and_not_for_others($p["program_id"], $other_programs_id, $program_rules, $rules_subjects).") AS toto";
//			$res = DataBase::query($q);
//			$nb = $res[0][0];
//			echo "<b>Finally</b>, excluding applicants eligible for previous programs, ".$nb." are eligible for ".$p["program_name"];
//		} else {
//			echo "<b>Total eligible applicants for ".$p["program_name"]." program:</b> ".nb_applicants_eligible_for_program($p["program_id"],$rules, $rules_subjects)."<br/>";
//		}
//	} else $all_ok = false;
//	echo "</div><br/>";
//	echo "</form>";
//        array_push($other_programs_id, $p["program_id"]);
//}

echo "<br/>";
if ($all_ok){
    //echo "Are you satisfied with these rules ? <a href='apply_rules.php?program_num=".$_GET['program_number'].">Apply rules to all applicants to set their eligibility in the database</a>";
    //echo 'Are you satified with these rules? <a href="apply_rules.php?program_num='.$_GET['program_number'].'">Apply rules to all applicants to set their eligibility in the database</a><br/>';
}else{
    echo "Please fix all the problems above before you can apply the rules";
}
echo "<br /><br />";
?>
<script type='text/javascript' language="javascript">
    function use_formula(avg,rule_id) {
        cancel_formula();
        var div = document.createElement('DIV');
        div.id = 'formula';
        var code = "<form name='formula_form' onsubmit='return false'>";
        code += "<center><div style='font-size:14pt;font-weight:bold'>Formula</div></center>";
        code += "<table cellspacing=0 cellpadding=2>";
        code += "<tr><td>Last Year Bar</td><td><input type='text' name='bar' size=6 maxlength=6/></td></tr>";
        code += "<tr><td>Last Year Average</td><td><input type='text' name='avg' size=6 maxlength=6/></td></tr>";
        code += "<tr><td>This Year Average</td><td>"+avg+"</td></tr>";
        code += "<tr><td colspan=2 align='center'><button onclick=\"calculate_formula('"+avg+"',"+rule_id+");return false\">Calculate</button></td></tr>";
        code += "<tr><td><b>This Year Bar</b></td><td><b id='formula_bar'></b></td></tr>";
        code += "<tr><td colspan=2 align='center'>";
        code += "<button id='formula_ok' onclick=\"ok_formula('"+avg+"',"+rule_id+");return false\" disabled='disabled'>Use bar</button>";
        code += " &nbsp; <button onclick=\"cancel_formula('"+avg+"',"+rule_id+");return false\">Cancel</button>";
        code += "</td></tr>";
        code += "</table>";
        code += "</form>";
        div.style.position = "fixed";
        div.style.left = "0px";
        div.style.top = "0px";
        div.style.borderStyle = "solid";
        div.style.borderWidth = "1px";
        div.style.borderColor = "#000000";
        div.style.backgroundColor = "#FFFFFF";
        div.style.padding = "3px";
        div.innerHTML = code;
        document.body.appendChild(div);
    }
    function cancel_formula() {
        var div = document.all ? document.all['formula'] : document.getElementById('formula');
        if (div != null) div.parentNode.removeChild(div);
    }
    function calculate_formula(avg,rule_id) {
        var form = document.forms['formula_form'];
        var ly_bar = form.elements['bar'].value;
        var ly_avg = form.elements['avg'].value;
        ly_bar = parseFloat(ly_bar);
        ly_avg = parseFloat(ly_avg);
        avg = parseFloat(avg);
        var bar = 0;
        if (ly_avg != 0){
            bar = Math.round(100*ly_bar*avg/ly_avg)/100;
            var e = document.all ? document.all['formula_bar'] : document.getElementById('formula_bar');
            e.innerHTML = bar;
            var e = document.all ? document.all['formula_ok'] : document.getElementById('formula_ok');
            e.innerHTML = "Use bar "+bar;
            e.disabled = '';
        }
    }
    function ok_formula(avg,rule_id) {
        var e = document.all ? document.all['formula_bar'] : document.getElementById('formula_bar');
        var bar = e.innerHTML;
        e = document.all ? document.all['mark_rule_'+rule_id] : document.getElementById('mark_rule_'+rule_id);
        e.value = bar;
        cancel_formula();
        location.href='?mark='+bar+'&rule='+rule_id+'#rule'+rule_id;
    }
</script>
<?php

include("../../footer.inc");
?>